package com.woniu.liuzhougov.authorityControl.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.liuzhougov.authorityControl.constant.UserConstant;
import com.woniu.liuzhougov.authorityControl.pojo.User;
import com.woniu.liuzhougov.authorityControl.pojo.UserStatus;
import com.woniu.liuzhougov.authorityControl.service.UserService;
import com.woniu.liuzhougov.authorityControl.service.UserStatusService;
import com.woniu.liuzhougov.authorityControl.utils.TableResult;
import com.woniu.liuzhougov.authorityControl.verification.Register;
import com.woniu.liuzhougov.common.utils.Result;
import com.woniu.liuzhougov.common.utils.ValidatedResult;
import com.woniu.liuzhougov.itemAndTask.pojo.Area;
import com.woniu.liuzhougov.itemAndTask.pojo.Department;
import com.woniu.liuzhougov.itemAndTask.service.AreaService;
import com.woniu.liuzhougov.itemAndTask.service.DepartmentService;
import com.woniu.liuzhougov.message.utils.MessageUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @version 1.0
 * @Author zhuxinpan
 * @ClassName UserController
 * @Description
 * @Date 2019/4/19 15:37
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserStatusService userStatusService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private AreaService areaService;

    /**
     * @return com.woniu.liuzhougov.common.utils.Result
     * @Author zhuxinpan
     * @Description 登录
     * @date 2019/4/22 9:51
     * @params [user]
     */
    @RequestMapping("/login")
    @ResponseBody
    public Result login(User user, String code, HttpServletRequest request) {

        //系统生成的验证码字符串
        String verifyCodeExpected = (String) request.getSession().getAttribute(
                com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

        //System.out.println(verifyCodeExpected);

        if (code.equals(verifyCodeExpected)) {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserLoginName(), user.getUserPass());
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
                //将当前登录用户信息存入session中
                subject.getSession().setAttribute(UserConstant.CURRENT_USER, subject.getPrincipal());
                return Result.success();
            } catch (UnknownAccountException e) {
                return Result.error("账号错误");
            } catch (IncorrectCredentialsException e) {
                return Result.error("密码错误");
            } catch (LockedAccountException e) {
                return Result.error("账号锁定");
            } catch (AuthenticationException e) {
                return Result.error("登录失败,请联系管理员");
            }
        } else {
            return Result.error("验证码错误");
        }
    }

    /*
     **
     * @Author Wuyuzhong
     * @Description 获取注册验证码
     * @Date 2019/4/30 15:24
     * @Param [phone, request]
     * @return java.lang.String
     **/
//    @RequestMapping("/getCode")
//    @ResponseBody
//    public String getCode(String phone, HttpServletRequest request){
//        String verifyCodeExpected = (String)request.getSession().getAttribute(
//                com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//        System.out.println(verifyCodeExpected);
//
//        //发送验证码
//        //phone:电话，code：验证码
//        MessageUtil.sendIdentifyingCode(phone,verifyCodeExpected);
//
//        return "success";
//    }

    /**
     * @param model
     * @return java.lang.String
     * @author zhuxinpan
     * @date 2019/4/28 10:51
     * @description 跳转到注册页面
     */
    @GetMapping("/register")
    public String register(Model model) {
        List<Department> departmentList = departmentService.listDepartments();
        List<Area> areaList = areaService.searchAllTypeOfArea();
        model.addAttribute("departmentList", departmentList);
        model.addAttribute("areaList", areaList);
        return "register";
    }

    /**
     * @param user
     * @return com.woniu.liuzhougov.common.utils.Result
     * @author zhuxinpan
     * @date 2019/4/28 12:51
     * @description 注册用户
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@Validated(value = {Register.class}) User user, BindingResult bindingResult, String code, HttpServletRequest request) {
        String verifyCodeExpected = (String) request.getSession().getAttribute("registerCode");
        if (code.equals(verifyCodeExpected)) {
            if (bindingResult.hasErrors()) {
                return Result.error(ValidatedResult.getValidateMessage("用户注册失败!", bindingResult));
            }
            if (userService.countLoginNameNumber(user) > 0) {
                return Result.error("登录名重复!");
            }
            UserStatus userStatus = new UserStatus();
            userStatus.setUserStatusId(UserConstant.USER_STATUS_NORMAL);
            user.setUserStatus(userStatus);
            if (userService.insertUser(user) == 0) {
                return Result.error("注册失败");
            }
            return Result.success("注册成功!");
        } else {
            return Result.error("验证码错误");
        }
    }

    /**
     * @return java.util.List<com.woniu.liuzhougov.authorityControl.pojo.User>
     * @Author zhuxinpan
     * @Description 展示所有用户
     * @date 2019/4/22 9:52
     * @params [currentPage, pageSize]
     */
    @RequestMapping("/listUser")
    @ResponseBody
    public TableResult listUser(User user, @RequestParam(required = false, defaultValue = "1", name = "page") Integer currentPage, @RequestParam(required = false, defaultValue = "5", name = "limit") Integer pageSize) {
        List<User> allUser = userService.listUser(user, currentPage, pageSize);
        PageInfo info = new PageInfo(allUser);
        TableResult tableResult = TableResult.getTableResult(allUser, info.getTotal());
        return tableResult;
    }

    /**
     * @return com.woniu.liuzhougov.common.utils.Result
     * @Author zhuxinpan
     * @Description 更新密码
     * @date 2019/4/23 9:41
     * @params [user]
     */
    @RequiresPermissions("user_updatePass")
    @PostMapping("/updatePass")
    @ResponseBody
    public Result updatePass(User user) {
        if (user.getUserId() == null || user.getUserPass() == null || "".equals(user.getUserPass())) {
            return Result.error("请检查输入的密码");
        }
        int updateResult = userService.updatePassByUserId(user);
        if (updateResult > 0) {
            return Result.success("密码修改成功");
        }
        return Result.error("密码修改失败");
    }

    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author zhuxinpan
     * @Description 接受参数, 跳转到更新密码页面
     * @date 2019/4/24 14:36
     * @params [userId]
     */
    @RequiresPermissions("user_updatePass")
    @GetMapping("/updatePass/{userId}")
    public ModelAndView updatePass(@PathVariable(name = "userId") Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("userId", userId);
        modelAndView.setViewName("account_manager_updatePass");
        return modelAndView;
    }

    /**
     * @return com.woniu.liuzhougov.common.utils.Result
     * @Author zhuxinpan
     * @Description 分配部门
     * @date 2019/4/23 17:01
     * @params [user]
     */
    @RequiresPermissions("user_updateDepartment")
    @RequestMapping("/updateDepartment")
    @ResponseBody
    public Result updateDepartment(User user) {
        if (user.getUserId() == null || user.getDepartment() == null || user.getDepartment().getDepartmentId() == null) {
            return Result.error("请求参数错误");
        }
        if (userService.updateDepartmentByUserId(user) == 0) {
            return Result.error("分配部门操作失败");
        }
        return Result.success("更改部门成功");
    }

    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author zhuxinpan
     * @Description 处理请求, 跳转到更新部门页面
     * @date 2019/4/24 16:49
     * @params [userId]
     */
    @RequiresPermissions("user_updateDepartment")
    @GetMapping("/updateDepartment/{userId}")
    public ModelAndView updateDepartment(@PathVariable(name = "userId") Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.getUserByUserId(userId);
        List<Department> departmentList = departmentService.listDepartments();
        modelAndView.addObject("user", user);
        modelAndView.addObject("departmentList", departmentList);
        modelAndView.setViewName("account_manager_distributionDepartment");
        return modelAndView;
    }

    /**
     * @return com.woniu.liuzhougov.common.utils.Result
     * @Author zhuxinpan
     * @Description 更新用户状态
     * @params [user]
     * @date 2019/4/23 23:03
     */
    @RequiresPermissions("user_updateUserStatus")
    @RequestMapping("/updateUserStatus")
    @ResponseBody
    public Result updateUserStatus(User user) {
        if (user.getUserId() == null || user.getUserStatus() == null || user.getUserStatus().getUserStatusId() == null) {
            return Result.error("请求参数错误");
        }
        if (userService.updateUserStatusByUserId(user) == 0) {
            return Result.error("状态更新失败");
        }
        return Result.success("状态更新成功");
    }

    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author zhuxinpan
     * @Description 转发到更新用户状态界面
     * @date 2019/4/24 16:46
     * @params [userId]
     */
    @RequiresPermissions("user_updateUserStatus")
    @GetMapping("/updateUserStatus/{userId}")
    public ModelAndView updateUserStatus(@PathVariable(name = "userId") Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.getUserByUserId(userId);
        List<UserStatus> userStatuses = userStatusService.listUserStatuses();
        modelAndView.addObject("user", user);
        modelAndView.addObject("userStatuses", userStatuses);
        modelAndView.setViewName("account_manager_updateUserStatus");
        return modelAndView;
    }

    /**
     * @return com.woniu.liuzhougov.common.utils.Result
     * @Author zhuxinpan
     * @Description 删除用户, 将用户状态改为注销状态, 不直接删除
     * @date 2019/4/24 18:56
     * @params [userId]
     */
    @RequiresPermissions("user_deleteUser")
    @DeleteMapping("/deleteUser/{userId}")
    @ResponseBody
    public Result deleteUser(@PathVariable(name = "userId") Integer userId) {
        User user = new User();
        user.setUserId(userId);
        UserStatus userStatus = new UserStatus();
        userStatus.setUserStatusId(UserConstant.USER_STATUS_DELETE);
        user.setUserStatus(userStatus);
        if (userService.updateUserStatusByUserId(user) > 0) {
            return Result.success("删除用户成功");
        }
        return Result.error("删除用户失败");
    }

    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author zhuxinpan
     * @Description 查看用户详情 准备数据并跳转页面
     * @date 2019/4/24 19:49
     * @params [userId]
     */
    @RequiresPermissions("user_viewDetails")
    @GetMapping("/viewDetails/{userId}")
    public ModelAndView viewDetails(@PathVariable(name = "userId") Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.getUserDetailByUserId(userId);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("account_manager_viewDetails");
        return modelAndView;
    }


    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author zhuxinpan
     * @Description 查询详细数据并, 跳转到信息修改页面
     * @date 2019/4/25 9:28
     * @params [userId]
     */
    @RequiresPermissions("user_viewDetails")
    @GetMapping("/modifyInfo/{userId}")
    public ModelAndView modifyInfo(@PathVariable(name = "userId") Integer userId) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.getUserDetailByUserId(userId);
        modelAndView.addObject("user", user);
        modelAndView.setViewName("account_manager_modifyInfo");
        return modelAndView;
    }

    /**
     * @return org.springframework.web.servlet.ModelAndView
     * @Author zhuxinpan
     * @Description 更新用户信息
     * @date 2019/4/25 9:39
     * @params [userId]
     */
    @RequiresPermissions("user_modifyInfo")
    @PostMapping("/modifyInfo")
    @ResponseBody
    public Result modifyInfo(User user) {
        if (user.getUserLoginName() == null || "".equals(user.getUserLoginName())) {
            return Result.error("登录名不能为空");
        }
        if (userService.countLoginNameNumber(user) > 0) {
            return Result.error("该登录名重复,请更换登录名称");
        }
        if (userService.updateUserDetails(user) == 0) {
            return Result.error("用户信息修改失败");
        }
        return Result.success("用户信息修改成功");
    }

    /**
     * @param
     * @return java.lang.String
     * @author zhuxinpan
     * @date 2019/5/5 14:54
     * @description 跳转到账号管理页面
     */
    @RequiresPermissions("account_manager")
    @GetMapping("/account/manager")
    public String manager() {
        return "account_manager";
    }

}
